package service

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"grpc/pb"
	"grpc/utils"
	"io"
	"log"
)

type GreeterServer struct {
	pb.UnimplementedGreeterServer
}

func (*GreeterServer) SayHi(context.Context, *pb.GreeterRequest) (*pb.GreeterReply, error) {
	log.Println("------普通的 rpc--测试异常是否被捕捉到了--------")
	panic("测试出差错了")
	return nil, status.Errorf(codes.Internal, "内部发生了错误")
}

func (*GreeterServer) TestHi(context.Context, *pb.GreeterRequest) (*pb.GreeterReply, error) {
	log.Println("------正常的请求--------")
	a := 12
	b := 13
	c := a / b
	println(c)
	return &pb.GreeterReply{Message: "成功执行方法"}, nil
}

type BattleServer struct {
	pb.BattleServer
}

func (*BattleServer) SayHello(stream pb.Battle_SayHelloServer) error {
	log.Println("---------rpc stream ---处理流异常测试-----------")
	a := 100
	b := 0
	c := a / b
	log.Println(c)
	req, err := stream.Recv()
	log.Println(err)
	log.Println(req.Name)
	if err == io.EOF {
		err = stream.SendMsg(&pb.HelloReply{})
		if err != nil {
			log.Println(err)
		}
	}
	return status.Errorf(codes.Unimplemented, "method SayHello not implemented")
}

func (*BattleServer) TestException(context.Context, *pb.HelloRequest) (*pb.HelloReply, error) {
	log.Println("--------TestException---处理流异常测试-----------")
	utils.Go(func() {
		log.Println("---------rpc stream ---处理流异常测试-----------")
		a := 100
		b := 0
		c := a / b
		log.Println(c)
	})
	return &pb.HelloReply{Message: "成功执行方法"}, nil
}
